<template>
  <div class="auBackground">
    <div class="auContent">
      <div>
        <el-input v-model="funSearch" placeholder="请输入功能名称">
          <el-button slot="append" icon="el-icon-search" @click="showDatas()" />
        </el-input>
      </div>
      <el-button
        type="primary"
        class="addButton"
        icon="el-icon-plus"
        @click="operaAuthority('创建')"
        >创 建</el-button
      >
    </div>
    <div class="tableContent">
      <el-row :gutter="20" type="flex" justify="center">
        <el-col :span="11">
          <div>
            <el-table
              v-loading="authLoading"
              :data="authorities"
              :header-cell-style="getRowClass"
              :row-style="RowClass"
              style="width: 100%"
              border
            >
              <el-table-column prop="name" label="名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作" width="220">
                <template slot-scope="scope">
                  <el-button-group>
                    <el-button
                      size="mini"
                      type="primary"
                      @click="operaAuthority('编辑', scope.$index, scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="info"
                      @click="manageApi(scope.$index)"
                      >管理</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      @click="deleteAuthority(scope.$index)"
                      >删除</el-button
                    >
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
            <div
              v-if="authorities.length !== 0"
              style="
                display: flex;
                flex-direction: row-reverse;
                margin-top: 10px;
              "
            >
              <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :total="count"
                :page-sizes="[10, 20, 50, 100]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-col>
        <el-col :span="13" style="display: flex; justify-content: center">
          <div v-if="addApi">
            <el-transfer
              v-loading="authDeviceLoading"
              v-model="value"
              :titles="titles"
              :button-texts="['移除', '添加']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}',
              }"
              :props="{
                key: '_id',
                label: 'name',
              }"
              :data="apiData"
              filterable
              style="
                text-align: left;
                display: inline-block;
                width: 100%;
                height: 100%;
              "
              @change="handleChange"
            />
          </div>
          <div v-if="!addApi" class="tips">
            <span class="tipsOne">没有选择功能哟</span>
            <span class="tipsTwo">
              <i class="el-icon-warning" />
              请选择一个功能并点击管理按钮进行api的管理
            </span>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      :visible.sync="operaDialog"
      :title="dialogTitle"
      width="30%"
      :modal-append-to-body="false"
    >
      <el-form
        ref="operaForm"
        :model="operaForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="operaForm.name" placeholder="请输入功能的名称" />
        </el-form-item>
        <!-- <el-form-item label="设备操作" prop="isDevice">
          <el-radio v-model="operaForm.isDevice" label="1">是</el-radio>
          <el-radio v-model="operaForm.isDevice" label="0">否</el-radio>
        </el-form-item> -->
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="operaForm.description"
            type="textarea"
            placeholder="请输入功能的描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
@import url("../../../styles/authority.scss");
</style>
<script>
import {
  addAuthority,
  showAuthority,
  delAuthority,
  updateAuthority
} from '@/api/power/auth.js'
import { findAllApi } from '@/api/power/api.js'
export default {
  data () {
    return {
      operaForm: {}, // 添加修改对象
      authorities: [], // 功能数据
      operaDialog: false, // 打开添加修改对话框
      apiData: [], // api列表 绑定全部api
      value: [], // 添加功能 绑定用户拥有的api
      opera: '', // 区分操作的参数
      titles: ['api列表'], // 穿梭框的标题
      funSearch: '', // 搜索查询的参数
      dialogTitle: '', // 添加修改窗口标题
      rules: {
        // 表单验证
        name: [
          { required: true, message: '请输入功能的名称', trigger: 'blur' }
        ],
        isDevice: [
          { required: true, message: '请选择是否为设备操作', trigger: 'change' }
        ]
      },
      index: -1, // 高亮的行
      pageSize: 10, // 分页的页面大小
      count: 0, // 分页的数据总数
      currentPage: 1, // 分页的当前页
      updateIndex: '', // 修改数据的index
      addApi: false, // 管理api
      authLoading: true, // 表格加载框
      authDeviceLoading: false // 权限设备加载框
    }
  },
  created () {
    // 页面渲染调出数据
    this.showData()
  },
  methods: {
    // api添加删除按钮
    handleChange (value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
      this.authDeviceLoading = true
      const updateFun = JSON.parse(
        JSON.stringify(this.authorities[this.updateIndex])
      )
      console.log('updateFun', updateFun)
      updateFun.apis = value
      updateAuthority(this.authorities[this.updateIndex]._id, updateFun).then(
        res => {
          console.log('updateAuthority', res)
          if (res.data.code === 1000) {
            this.authorities.splice(this.updateIndex, 1, updateFun)
            this.$message({
              center: true,
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message.error({
              center: true,
              message: res.errmsg
            })
          }
          this.authDeviceLoading = false
        }
      )
    },
    // 筛选调出数据
    showDatas () {
      this.authLoading = true
      this.currentPage = 1
      this.showData()
    },
    // 修改点击行颜色
    RowClass ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === this.index) {
        return 'background: #DDF3FF;'
      } else {
        return ''
      }
    },
    // 修改表格样式
    getRowClass ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background: rgb(240,245,250);color:black '
      } else {
        return ''
      }
    },
    // 重置按钮
    resetForm () {
      this.$refs.operaForm.resetFields()
    },
    // 添加修改窗口打开
    operaAuthority (title, index, rows) {
      if (title === '编辑') {
        this.operaForm = JSON.parse(JSON.stringify(this.authorities[index]))
        this.updateIndex = index
        this.opera = 'update'
      } else {
        this.operaForm = {}
        this.opera = 'add'
      }
      this.operaDialog = true
      this.dialogTitle = title
    },
    // 添加修改提交
    submitForm () {
      this.$refs.operaForm.validate(valid => {
        if (valid) {
          if (this.opera === 'add') {
            addAuthority(this.operaForm).then(res => {
              console.log('addAuthority', res)
              if (res.data.code === 1000) {
                this.authLoading = true
                this.showData()
                this.operaDialog = false
                this.$message({
                  center: true,
                  message: '添加成功',
                  type: 'success'
                })
              } else {
                this.$message.error({
                  center: true,
                  message: res.errmsg
                })
              }
            })
          } else {
            updateAuthority(this.operaForm._id, this.operaForm).then(res => {
              console.log('res:', res)
              if (res.data.code === 1000) {
                this.authorities.splice(
                  Number(this.updateIndex),
                  1,
                  this.operaForm
                )
                this.operaDialog = false
                this.$message({
                  center: true,
                  message: '修改成功',
                  type: 'success'
                })
              } else if (res.data.code === 1022) {
                this.$message.error({
                  center: true,
                  message: '该功能不存在,请刷新后重试'
                })
              } else {
                this.$message.error({
                  center: true,
                  message: res.errmsg
                })
              }
            })
          }
        } else {
          this.$message({
            showClose: true,
            message: '请根据要求将信息填写完整',
            type: 'warning'
          })
        }
      })
    },
    // 管理api
    manageApi (index, rows) {
      console.log('index', index)
      this.index = index
      this.updateIndex = index
      this.addApi = true
      this.authDeviceLoading = true
      findAllApi().then(res => {
        // console.log('findAllApi', res)
        if (res.data.code === 1000) {
          console.log(res)
          this.apiData = res.data.data.Api
          this.value = this.authorities[index].apis
          if (this.value === null) {
            this.value = []
          }
          // console.log('value', this.value)
        } else {
          this.$message.error({
            center: true,
            message: res.errmsg
          })
        }
        this.authDeviceLoading = false
      })
      // console.log('role:', this.authorities)
      // this.value = this.authorities[index].YesApi
      // this.value = this.authorities[index].apis
      // console.log('value', this.value)
      // this.value = this.authorities[index].ApiPermission
      this.titles.splice(1, 1, this.authorities[index].name)
      this.operaForm = JSON.parse(JSON.stringify(this.authorities[index]))
    },
    // 删除功能
    deleteAuthority (index, rows) {
      this.$confirm('此操作将永久删除该功能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delAuthority(this.authorities[index]).then(res => {
            console.log('delAuthority', res)
            if (res.data.code === 1000) {
              this.authLoading = true
              this.showData()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error({
                center: true,
                message: res.errmsg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 改变页面大小
    handleSizeChange (value) {
      this.authLoading = true
      this.pageSize = value
      this.showData()
    },
    // 改变页数
    handleCurrentChange (value) {
      this.authLoading = true
      this.currentPage = value
      this.showData()
    },
    // 遍历数据
    showData () {
      // var searchName = ''
      var search = ''
      if (this.funSearch.length !== 0) {
        // searchName += 'name'
        search = this.funSearch
      }
      // 组织参数
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        key: search
        // searchName: searchName
      }
      showAuthority(params).then(res => {
        console.log('showAuthority', res)
        this.authLoading = false
        // this.authorities = res.data.data
        // for (let i = 0; i < this.authorities.length; i++) {
        //   this.value[i] = this.authorities[i].apis
        // }
        // console.log('value', this.value)

        // this.pageSize = res.data.pageSize
        // this.currentPage = res.data.currentPage
        if (res.data.code === 1000) {
          if (res.data.data !== null) {
            // this.count = res.data.data.count
            // this.pageSize = res.data.data.pageSize
            // this.currentPage = res.data.data.currentPage
            this.authorities = res.data.data
          } else {
            this.authorities = []
            this.$message({
              type: 'warning',
              message: '功能数据为空!'
            })
          }
        }
        //   this.authLoading = false
        // }
      })
    }
  }
}
</script>
